<template>
  <div class="page-main">
    <query-page
      v-model:selectedKeys="selectedKeys"
      :form-component-config="formComponentConfig"
      :form-render-config="formRenderConfig"
      :form-render-keys="formRenderKeys"
      :table-component-config="tableComponentConfig"
      :table-render-config="tableRenderConfig"
      :table-render-keys="tableRenderKeys"
      :loading="isLoading"
      :data="renderData"
      :total="total"
      title="选商方式确认"
      :has-line="false"
      row-selection-type="checkbox"
      @query-data="getData"
    >
      <template #top-container>
        <p-tabs
          v-model:value="activeTab"
          :is-show-num="true"
          :tab-list="tabList"
        ></p-tabs>
      </template>
      <template #container-side>
        <a-space>
          <a-button
            v-permission="['procurement:plan-list:updateBill']"
            type="primary"
            :disabled="selectedKeys.length === 0"
            @click="handlePoint"
            >指定选商方式</a-button
          >
          <a-button
            v-permission="['procurement:plan-list:doApproval']"
            :disabled="selectedKeys.length === 0"
            @click="handleReject"
            >驳回</a-button
          >
          <a-button
            v-if="activeRadio === '1'"
            v-permission="['procurement:plan-list:updatePlanForXjd:planList']"
            :disabled="selectedKeys.length === 0"
            @click="handleCon"
            >确认</a-button
          >
          <a-button
            v-if="activeRadio !== '1'"
            v-permission="['procurement:plan-file:supBatchSave:planList']"
            :disabled="selectedKeys.length === 0"
            @click="compilechange"
            >批量上传供应商选择文件</a-button
          >
          <a-button
            v-if="activeRadio === '2'"
            v-permission="['procurement:plan-supplier:obtainSupplier']"
            :disabled="selectedKeys.length === 0"
            @click="handleUpdate"
            >更新供应商</a-button
          >
          <a-button
            v-if="['2', '3', '4', '5'].includes(activeRadio)"
            v-permission="['procurement:supplier-chose-result:batchSave']"
            :disabled="selectedKeys.length === 0"
            @click="handleConfirm"
            >{{
              activeRadio === '5' ? '招标完成生成选商结果' : '确认生成选商结果'
            }}</a-button
          >
          <a-button
            v-if="['0', '2'].includes(activeRadio)"
            v-permission="[
              'procurement:plan-list:exportCpWzd',
              'procurement:plan-list:importYclWzd',
              'procurement:plan-list:exportBzjWzd',
              'procurement:plan-list:exportLzjWzd',
              'procurement:plan-list:exportDzjWzd',
              'procurement:plan-list:exportDyly',
            ]"
            @click="exportCpWzdapi"
            >Excel导出</a-button
          >
          <a-button
            v-if="['0', '2'].includes(activeRadio)"
            v-permission="[
              'procurement:plan-list:importCpWzd',
              'procurement:plan-list:importYclWzd',
              'procurement:plan-list:importBzjWzd',
              'procurement:plan-list:importLzjWzd',
              'procurement:plan-list:importDzjWzd',
              'procurement:plan-list:importDyly',
            ]"
            @click="handleExcel"
            >{{ activeRadio === '0' ? 'Excel导入指定选商' : 'Excel导入'
            }}<a-tooltip
              v-if="['0'].includes(activeRadio)"
              :content="content"
              background-color="#165DFF"
            >
              <icon-exclamation-circle /> </a-tooltip
          ></a-button>
        </a-space>
      </template>
      <template #header-ext-container>
        <a-radio-group
          v-model="activeRadio"
          type="button"
          style="margin-top: 16px"
          @change="handleChangegroup"
        >
          <a-radio value="0">未指定</a-radio>
          <a-radio value="1">询价采购</a-radio>
          <a-radio value="2">单一来源采购</a-radio>
          <a-radio value="3">比选采购</a-radio>
          <a-radio value="4">竞争性谈判采购</a-radio>
          <a-radio value="5">招投标</a-radio>
        </a-radio-group>
      </template>
      <template #attachment="{ record }">
        <a-popover
          title="查看附件"
          trigger="click"
          content-style="max-height:300px;overflow: auto;"
        >
          <a-button
            v-permission="['procurement:plan-file:getPlanFileListByplanListNo']"
            type="text"
            @click="handleAttachment(record)"
            >查看附件</a-button
          >
          <template #content>
            <div v-if="attachmentList.length === 0">-</div>
            <div
              v-for="(item, index) in attachmentList"
              :key="index"
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <p>{{ item.fileName }}</p>
              <div>
                <span
                  style="margin: 0 10px; color: #165dff; cursor: pointer"
                  @click="handleDown(item)"
                  >下载</span
                ><span
                  v-permission="['procurement:plan-file:delete']"
                  style="color: red; cursor: pointer"
                  @click="handleDel(item, index)"
                  >删除</span
                >
              </div>
            </div>
          </template>
        </a-popover>
      </template>
      <template #operate="{ record }">
        <a-button
          v-permission="['procurement:plan-file:supBatchSave:planList']"
          type="text"
          :hidden="!['1', '2'].includes(activeRadio)"
          @click="compilechange(record)"
        >
          供应商选择文件上传
        </a-button>
        <a-button
          v-permission="['procurement:plan-supplier:batchUpdateForSimple']"
          type="text"
          :hidden="!['1', '2'].includes(activeRadio)"
          @click="handleEdit(record)"
        >
          编辑
        </a-button>
        <a-button
          v-permission="['procurement:plan-supplier:batchSaveOrUpdate']"
          type="text"
          :hidden="!['3', '4', '5'].includes(activeRadio)"
          @click="handleDetail(record)"
        >
          详情
        </a-button>
        <a-button
          v-permission="['procurement:tender:saveOrUpdate']"
          type="text"
          :hidden="!['5'].includes(activeRadio)"
          @click="handleUpLoad(record)"
        >
          上传文件
        </a-button>
      </template>
    </query-page>
    <!-- 文件导入  -->
    <fileUpload
      v-if="fileValueflag"
      v-model="fileValue"
      :selected-id="attachmentUploadList"
      type="2"
      btn-name="文件上传"
      btn-type="text"
      title="Excel导入"
      accept=".xlsx"
      :max-size="10"
      @restion="fileValueflagfun"
    />
    <!-- 批量上传 -->
    <batchImport
      v-if="batchVisible"
      export-type="apiUrl"
      title="Excel导入"
      :file-code="excelObj[`${activeTab}${activeRadio}`].code"
      :import-url="excelObj[`${activeTab}${activeRadio}`].importurl"
      :dispflag="displflag"
      @close-drawer="closeDrawer"
      @finish="finish"
    ></batchImport>
    <singleProcurementModel
      v-if="singleProShow"
      ref="singlePro"
      v-model:singleProShow="singleProShow"
      @handleClose="handleClose"
    ></singleProcurementModel>
    <viewDetail
      v-if="viewDetailShow"
      ref="viewDetailRef"
      v-model:viewDetailShow="viewDetailShow"
    ></viewDetail>
    <uploadEdit
      v-if="upLoadEditShow"
      ref="upLoadEditRef"
      v-model:upLoadEditShow="upLoadEditShow"
      @handleCancel="handleCancel"
    ></uploadEdit>
    <a-modal :visible="pointVisible" @ok="pointOk" @cancel="pointCancel">
      <template #title> 指定选商方式： </template>
      <span>选商方式：</span>
      <dict-select
        v-model="pointValue"
        style="width: 200px"
        allow-clear
        dict-type="businessSelectionStrategy"
        placeholder="请选择"
      ></dict-select>
    </a-modal>
    <a-modal :visible="rejectVisible" @ok="rejectOk" @cancel="rejectCancel">
      <template #title> 批量驳回： </template>
      <span>驳回原因：</span>
      <a-textarea
        v-model="rejectReason"
        placeholder="最大输入1000字符"
        :max-length="{ length: 1000, errorOnly: true }"
        allow-clear
        show-word-limit
      />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import dictSelect from '@/common/components/dict-select/index.vue';
  import { nextTick, onMounted, ref, watch } from 'vue';
  import {
    getPlanListForBill, // 选商方式 （0-未指定 3-比选采购 4-竞争性谈判采购 5-招投标）
    getPlanListForXjcg, // 选商方式 （1-询价采购）
    getPlanListForDyly, // 选商方式 （2-单一来源） getPlanListForDyly
    getPlanListForZtb, // 选商方式 （5-招投标）
    updateBill,
    doApproval,
    obtainSupplier,
    updateInquiryStatus,
    batchSave,
    exportCpWzd,
    exportYclWzd,
    exportBzjWzd,
    exportDzjWzd,
    exportLzjWzd,
    exportDyly,
    getPlanFileListByplanListNo,
    delPlanFile,
  } from '@/api/supplier/selective-quotient';
  import queryPage from '@/common/components/query-page/index.vue';
  import { Message, Modal } from '@arco-design/web-vue';
  import { downFileToExcel } from '@/common/utils/downFile';
  import batchImport from '@/common/components/batch-import/import-container.vue';
  import lodash from 'lodash';
  import fileUpload from './components/file-upload-page/index.vue';
  import PTabs from './components/p-tabs.vue';
  import viewDetail from './components/detailChild.vue';
  import uploadEdit from './components/uploadEdit.vue';
  import {
    formRenderConfig,
    formComponentConfig,
  } from './components/formComp/baseFormConfig';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from './components/tableComp/baseTableConfig';
  import baseRenderKeys from './components/tableComp/renderTableColumns';
  import formRender from './components/formComp/formRender';
  import singleProcurementModel from './components/single-procurement-model.vue';

  const batchVisible = ref(false); // 批量上传
  const rejectVisible = ref(false);
  const rejectReason = ref();
  const pointVisible = ref(false);
  const pointValue = ref();
  const singleProShow = ref(false);
  const singlePro = ref();
  const viewDetailShow = ref(false);
  const viewDetailRef = ref();
  const upLoadEditShow = ref(false);
  const upLoadEditRef = ref();
  const activeRadio = ref('0');
  const fileValueflag = ref(false); // 表单单条信息详情开关
  const fileValue = ref({});
  const displflag = ref(false); // 上传文件模板显示/隐藏
  // 渲染检索项
  const formRenderKeys = ref<any[]>([]);
  const activeTab = ref('2');
  const selectedKeys = ref<any[]>([]);
  const tableRenderKeys = ref<any[]>([]);
  const isLoading = ref(true);
  const renderData = ref<any[]>([]);
  const queryInfoList = ref();
  const total = ref(0);
  const attachmentList = ref([]);
  const tabList = ref([
    { label: '成品', id: '2' },
    { label: '原材料', id: '3' },
    { label: '标准件', id: '1' },
    { label: '零组件', id: '4' },
    { label: '锻铸件', id: '5' },
  ]);
  const content = ref(
    '请先【Excel导出】，修改“选商方式”信息之后，在进行【Excel导入指定选商】，可对未指定的采购计划，进行选商方式的指定。'
  );
  const getData = async (queryInfo: object) => {
    queryInfoList.value = queryInfo;
    // 0-未指定 3-比选采购 4-竞争性谈判采购
    if (['0', '3', '4'].includes(activeRadio.value)) {
      getDataList(activeRadio.value, activeTab.value);
    }
    // 1-询价采购
    if (['1'].includes(activeRadio.value)) {
      getDataList2(activeTab.value);
    }
    // 2-单一来源
    if (['2'].includes(activeRadio.value)) {
      getDataList3(activeTab.value);
    }
    // 5-招投标
    if (['5'].includes(activeRadio.value)) {
      getDataList4(activeTab.value);
    }
    selectedKeys.value = [];
  };
  // 获取列表数据 选商方式 （0-未指定 3-比选采购 4-竞争性谈判采购 5-招投标）
  const getDataList = async (billPolicy: string, mdsItemType: any) => {
    renderData.value = [];
    isLoading.value = true;
    const { data } = await getPlanListForBill({
      billPolicy: billPolicy || '0',
      mdsItemType: mdsItemType || '2',
      // supplierCode: 'HK_00001',
      ...queryInfoList.value,
    });
    renderData.value = data.list;
    total.value = data.total;
    isLoading.value = false;
  };
  // 获取列表数据 选商方式 （1-询价采购）
  const getDataList2 = async (queryInfo: any) => {
    renderData.value = [];
    isLoading.value = true;
    const { data } = await getPlanListForXjcg({
      billPolicy: '1',
      mdsItemType: queryInfo || 2,
      ...queryInfoList.value,
    });
    renderData.value = data.list;
    total.value = data.total;
    isLoading.value = false;
  };
  // 获取列表数据 选商方式 （2-单一来源）
  const getDataList3 = async (queryInfo: any) => {
    renderData.value = [];
    isLoading.value = true;
    const { data } = await getPlanListForDyly({
      billPolicy: '2',
      mdsItemType: queryInfo || 2,
      ...queryInfoList.value,
    });
    renderData.value = data.records;
    total.value = data.total;
    isLoading.value = false;
  };

  // 获取列表数据 选商方式 （5-招投标）
  const getDataList4 = async (queryInfo: any) => {
    renderData.value = [];
    isLoading.value = true;
    const { data } = await getPlanListForZtb({
      billPolicy: '5',
      mdsItemType: queryInfo || 2,
      ...queryInfoList.value,
    });
    renderData.value = data.records;
    total.value = data.total;
    isLoading.value = false;
  };
  const fileValueflagfun = (flag: any) => {
    fileValueflag.value = flag;
  };
  const handleChangegroup = async (val) => {
    displflag.value = val !== '0';
    activeRadio.value = val;
    selectedKeys.value = [];
    initData();
    getData();
  };
  const handlePoint = () => {
    pointVisible.value = true;
  };
  const handleAttachment = async (record) => {
    const { data } = await getPlanFileListByplanListNo(record.planListNo);
    attachmentList.value = data;
    console.log(data);
  };
  const pointOk = async () => {
    if (!pointValue.value) {
      Message.warning('请选择选商方式');
      return;
    }
    const result = selectedKeys.value.map((id) => ({
      id,
      billPolicy: pointValue.value,
    }));
    const { data } = await updateBill([...result]);
    Message.success(data);
    pointCancel();
    getData();
  };
  const rejectCancel = () => {
    rejectVisible.value = false;
    rejectReason.value = '';
  };
  const handleReject = () => {
    rejectVisible.value = true;
  };
  const rejectOk = async () => {
    if (!rejectReason.value) {
      Message.warning('请填写驳回原因');
      return;
    }
    const result = selectedKeys.value.map((id) => ({
      id,
      rejectReason: rejectReason.value,
      businessStatus: 4,
    }));
    const { data } = await doApproval([...result]);
    Message.success(data);
    rejectCancel();
    getData();
  };
  const pointCancel = () => {
    pointVisible.value = false;
    pointValue.value = '';
  };
  const handleCon = () => {
    Modal.warning({
      title: '请确认',
      content: '您确定要执行确认操作？',
      hideCancel: false,
      onOk: async () => {
        const result = selectedKeys.value.map((id) => ({
          id,
          inquiryStatus: 1,
        }));
        const { data } = await updateInquiryStatus([...result]);
        if (data) {
          Message.success('操作成功');
        }
        getData();
      },
    });
  };
  const handleUpdate = () => {
    const arr = selectedKeys.value.map((v) => {
      return renderData.value.find((m) => v === m.id).planListNo;
    });
    Modal.warning({
      title: '请确认',
      content: '您确定要更新供应商？',
      hideCancel: false,
      onOk: async () => {
        const { data } = await obtainSupplier(arr);
        if (data) {
          Message.success(data);
        }
        getData();
      },
    });
  };
  const handleConfirm = () => {
    const arr = selectedKeys.value.map((v) => {
      return renderData.value.find((m) => v === m.id).planListNo;
    });
    Modal.warning({
      title: '请确认',
      content: '您确定要执行确认选商结果？',
      hideCancel: false,
      onOk: async () => {
        const { data } = await batchSave(arr);
        if (data) {
          Message.success(data);
        }
        getData();
      },
    });
  };
  const handleClose = () => {
    getData();
  };
  // 初始化tab切换数据
  const initData = async () => {
    selectedKeys.value = [];
    const key = `${activeTab.value}${activeRadio.value}`;
    tableRenderKeys.value = baseRenderKeys[key];
    console.log(formRender[activeTab.value], activeTab.value);
    formRenderKeys.value = formRender[activeTab.value];
  };
  const attachmentUploadList = ref([]);
  // 供应商 文件上传
  const compilechange = (val) => {
    if (val.id) {
      selectedKeys.value = [val.id];
    }
    attachmentUploadList.value = selectedKeys.value.map((v) => {
      return renderData.value.find((m) => v === m.id).planListNo;
    });

    fileValueflag.value = true;
  };
  const handleEdit = (record) => {
    if (!record.supplierCode) {
      Message.warning('请先更新供应商在进行编辑操作');
      return;
    }
    singleProShow.value = true;
    nextTick(() => {
      singlePro.value.init(lodash.cloneDeep(record));
    });
  };
  const handleUpLoad = (record) => {
    upLoadEditShow.value = true;
    nextTick(() => {
      upLoadEditRef.value.init(record);
    });
  };
  // 批量上传
  const closeDrawer = (flag: boolean) => {
    console.log(flag, '关闭弹窗');
    batchVisible.value = flag;
  };
  const handleDel = async (val, index) => {
    const { data } = await delPlanFile([val.id]);
    if (data) {
      attachmentList.value.splice(index, 1);
      Message.success('删除成功');
    }
  };
  const handleDown = (val) => {
    window.open(val.url);
  };
  // 批量上传后的完成事件
  const finish = async (response: any, secretLevel: string, flag: boolean) => {
    batchVisible.value = flag;
    getData();
  };
  const excelObj = ref({
    20: {
      api: exportCpWzd,
      code: '',
      importurl: '/api/procurement/require/excelOperation/importCpWzd',
    },
    22: {
      api: exportDyly,
      code: 'require_planDylyUrl',
      importurl: '/api/procurement/require/excelOperation/importDyly',
    },
    30: {
      api: exportYclWzd,
      code: '',
      importurl: '/api/procurement/require/excelOperation/importYclWzd',
    },
    32: {
      api: exportDyly,
      code: 'require_planDylyUrl',
      importurl: '/api/procurement/require/excelOperation/importDyly',
    },
    10: {
      api: exportBzjWzd,
      code: '',
      importurl: '/api/procurement/require/excelOperation/importBzjWzd',
    },
    12: {
      api: exportDyly,
      code: 'require_planDylyUrl',
      importurl: '/api/procurement/require/excelOperation/importDyly',
    },
    40: {
      api: exportLzjWzd,
      code: '',
      importurl: '/api/procurement/require/excelOperation/importLzjWzd',
    },
    42: {
      api: exportDyly,
      code: 'require_planDylyUrl',
      importurl: '/api/procurement/require/excelOperation/importDyly',
    },
    50: {
      api: exportDzjWzd,
      code: '',
      importurl: '/api/procurement/require/excelOperation/importDzjWzd',
    },
    52: {
      api: exportDyly,
      code: 'require_planDylyUrl',
      importurl: '/api/procurement/require/excelOperation/importDyly',
    },
  });
  const handleExcel = () => {
    batchVisible.value = true;
  };
  // 导出
  const exportCpWzdapi = async () => {
    const key = `${activeTab.value}${activeRadio.value}`;
    const { data, fileName } = await excelObj.value[key].api({
      mdsItemType: activeTab.value,
      ...queryInfoList.value,
    });
    downFileToExcel(fileName, data);
  };
  const handleDetail = (record) => {
    viewDetailShow.value = true;
    nextTick(() => {
      viewDetailRef.value.init(record);
      viewDetailRef.value.activeRadio = activeRadio.value;
      viewDetailRef.value.tableRenderKeys =
        baseRenderKeys[
          `${activeTab.value}${activeRadio.value}${activeRadio.value}`
        ];
    });
  };
  const handleCancel = () => {
    upLoadEditShow.value = false;
    getData();
  };
  // 监听activeTab变化，更新状态和初始化数据
  watch(activeTab, () => {
    activeRadio.value = '0';
    selectedKeys.value = [];
    initData();
    getData();
  });
  // 组件挂载时的初始化操作
  onMounted(() => {
    activeTab.value = '2';
    activeRadio.value = '0';
    initData();
  });
</script>

<style lang="less" scoped>
  /deep/ .arco-radio-group-button {
    width: 100%;
  }

  /deep/ .arco-radio-button {
    width: 50%;
    color: #4e5769 !important;
    text-align: center;
  }

  /deep/ .arco-radio-button.arco-radio-checked {
    color: #1e2228 !important;
  }
</style>
